﻿using FlyingEye.Come;
using FlyingEye.Come.Repositories;
using FlyingEye.Exceptions;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Validation;

namespace FlyingEye.ComServices
{
    public class ComeUserService : ApplicationService
    {
        private readonly IComeUserRepository _comeUserRepository;

        public ComeUserService(IComeUserRepository comeUserRepository)
        {
            _comeUserRepository = comeUserRepository;
        }

        public async Task DeleteAsync(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new AbpValidationException("id 为空");
            }

            if (!await _comeUserRepository.AnyAsync(item => item.Id == id))
            {
                throw new ResourceNotFoundException($"用户 id = {id} 已存在。");
            }

            await _comeUserRepository.DeleteAsync(id);
        }

        public async Task<ComeUserResponse> GetAsync(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new AbpValidationException("id 为空");
            }

            var model = await _comeUserRepository.GetAsync(id);

            return ObjectMapper.Map<ComeUserModel, ComeUserResponse>(model);
        }

        public async Task<List<ComeUserResponse>> GetListAsync()
        {
            var users = await _comeUserRepository.GetListAsync();

            if (users.Any())
            {
                return ObjectMapper.Map<List<ComeUserModel>, List<ComeUserResponse>>(users);
            }

            return new List<ComeUserResponse>(0);
        }

        public async Task<ComeUserResponse> InsertAsync(CreateComeUserRequest comeUser)
        {
            if (await _comeUserRepository.AnyAsync(item => item.Id == comeUser.Id))
            {
                throw new AbpValidationException($"用户ID[{comeUser.Id}]已经被使用。");
            }

            var model = ObjectMapper.Map<CreateComeUserRequest, ComeUserModel>(comeUser);

            model = await _comeUserRepository.InsertAsync(model);

            return ObjectMapper.Map<ComeUserModel, ComeUserResponse>(model);
        }

        public async Task<ComeUserResponse> UpdateAsync(UpdateComeUserRequest comeUser)
        {
            var user = await _comeUserRepository.FindAsync(comeUser.Id);

            if (user == null)
            {
                throw new ResourceNotFoundException($"用户[${comeUser.Id}]不存在。");
            }

            if (user.UserName == comeUser.UserName)
            {
                return ObjectMapper.Map<ComeUserModel, ComeUserResponse>(user);
            }

            ObjectMapper.Map(comeUser, user);

            user = await _comeUserRepository.UpdateAsync(user);

            return ObjectMapper.Map<ComeUserModel, ComeUserResponse>(user);
        }
    }
}
